<template>
  <div class="tree-container">
    <el-tabs
      v-model="activeName"
      style="height: 100%; margin-top: 4px"
      @tab-click="handleClick"
    >
      <!-- 公司 -->
      <el-tab-pane label="公司" style="height: 100%" name="first">
        <div>
          <el-row>
            <el-col
              :span="8"
              class="numStatus"
              :class="activeNum == 1 ? 'active' : ''"
              style="color: black"
            >
              <span @click="getCompanyTree()">全部({{ company.allNum }})</span>
            </el-col>
            <el-col
              :span="8"
              class="numStatus"
              :class="activeNum == 2 ? 'active' : ''"
              style="color: green"
            >
              <span @click="clickNum(2)">在线({{ company.onlineNum }})</span>
            </el-col>
            <el-col
              :span="8"
              class="numStatus"
              :class="activeNum == 3 ? 'active' : ''"
              style="color: red"
            >
              <span @click="clickNum(3)">离线({{ company.offlineNum }})</span>
              <div style="margin-left: 5px" @click="getOffLineNum">
                <i class="el-icon-caret-bottom"></i>
              </div>
            </el-col>
          </el-row>

          <div class="searchbox flex-center">
            <el-input
              v-model="input"
              placeholder="输入环保编号、档案号、名称查询"
              style="width: 200px; margin: 0 10px"
              size="mini"
            ></el-input>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="companyKeySearch"
              >搜索</el-button
            >
          </div>

          <!-- 点搜索出来的弹窗 -->
          <el-dialog
            title="按离线时间统计数量"
            :visible.sync="offLineSearch"
            :append-to-body="true"
            width="30%"
          >
            <div class="flex-center">
              <label>离线时间：</label>
              <el-date-picker
                v-model="dateTime"
                type="datetime"
                size="mini"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="      选择日期"
                :picker-options="pickerOptions"
              >
              </el-date-picker>
              &emsp;
              <el-button type="primary" @click="getOffLineCarNum" size="mini">
                确定
              </el-button>
            </div>

            <div style="margin-top: 20px">
              <label>
                离线数量：<span style="color: red">{{ offLineNum }}</span>
              </label>
            </div>

            <div slot="footer" class="dialog-footer">
              <el-button @click="offLineSearch = false" size="mini"
                >关闭</el-button
              >
            </div>
          </el-dialog>
        </div>

        <!-- 公司区域树 -->
        <div class="treedata">
          <el-tree
            :data="companyTree"
            show-checkbox
            node-key="id"
            :props="defaultProps"
            ref="refcompany"
            accordion
            @check="companyCheck"
          >
          </el-tree>
        </div>
      </el-tab-pane>

      <!-- 区域 -->
      <el-tab-pane label="区域" style="height: calc(60vh - 74px)" name="second">
        <div>
          <el-button
            style="margin: 0 0 10px 10px"
            @click="searchCarinfoShow = !searchCarinfoShow"
            type="primary"
            size="mini"
          >
            类型搜索<i class="el-icon-search"></i>
          </el-button>
        </div>

        <!-- 省市区的树 -->
        <div class="areaTree">
          <el-tree
            :data="areaTree"
            show-checkbox
            node-key="id"
            :props="defaultProps"
            ref="areaTree"
            accordion
            highlight-current
            @check="allcheck"
          >
          </el-tree>
        </div>
        <!-- 点搜索出来的弹窗 -->
        <div
          v-show="searchCarinfoShow"
          class="searchCarinfobox"
          @click="searchCarinfoShow = true"
        >
          <el-form
            :model="searchCarinfoForm"
            ref="searchCarinfoForm"
            label-width="70px"
            size="mini"
          >
            <el-form-item label="车辆分类" prop="classification">
              <el-input
                type="text"
                v-model="searchCarinfoForm.classification"
                readonly
                style="width: 150px"
              ></el-input>
              <i
                class="el-icon-search cpnc"
                @click="searchCarinfo('cartype')"
              ></i>
            </el-form-item>
            <el-form-item label="车辆品牌" prop="brand">
              <el-input
                type="text"
                v-model="searchCarinfoForm.brand"
                readonly
                style="width: 150px"
              ></el-input>
              <i
                class="el-icon-search cpnc"
                @click="searchCarinfo('carbrand')"
              ></i>
            </el-form-item>
            <el-form-item label="车辆型号" prop="model">
              <el-input
                type="text"
                v-model="searchCarinfoForm.model"
                readonly
                style="width: 150px"
              ></el-input>
              <i
                class="el-icon-search cpnc"
                @click="searchCarinfo('carmodel')"
              ></i>
            </el-form-item>
            <el-form-item class="flex">
              <el-button type="primary" @click="searchBtn('searchCarinfoForm')"
                >搜索</el-button
              >
              <el-button @click="resetBtn">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 车辆分类 -->
    <el-dialog :visible.sync="cardTypeShow" title="请选择车辆分类" width="30%">
      <div class="dialog-content">
        <el-input
          placeholder="输入关键字进行过滤"
          v-model="filterText"
          size="mini"
        >
        </el-input>

        <div style="height: 340px; overflow-y: scroll">
          <el-tree
            class="filter-tree"
            node-key="id"
            :data="typeTreeData"
            :props="defaultProps"
            :filter-node-method="filterNode"
            show-checkbox
            @check="carTypeCheck"
            ref="typetree"
          >
          </el-tree>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cardTypeShow = false">取 消</el-button>
        <el-button type="primary" @click="checkedval">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 车辆品牌 -->
    <el-dialog :visible.sync="cardBrandShow" title="请选择车辆品牌" width="30%">
      <div class="dialog-content">
        <el-input
          placeholder="输入关键字进行过滤"
          v-model="brandfilterText"
          size="mini"
        >
        </el-input>

        <div style="height: 340px; overflow-y: scroll">
          <el-tree
            class="filter-tree"
            node-key="id"
            :data="brandTreeData"
            :props="defaultProps"
            :filter-node-method="filterNode"
            show-checkbox
            @check="carBrandCheck"
            ref="brandtree"
          >
          </el-tree>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cardBrandShow = false">取 消</el-button>
        <el-button type="primary" @click="carBrandCheckval">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 车辆型号 -->
    <el-dialog
      :visible.sync="cardModelShow"
      @close="cardModelClose"
      destroy-on-close
      title="请选择车辆型号"
      width="30%"
    >
      <div class="dialog-content">
        <el-input
          placeholder="输入关键字进行过滤"
          v-model="modelfilterText"
          size="mini"
        >
        </el-input>
        <div style="height: 340px; overflow-y: scroll">
          <el-tree
            class="filter-tree"
            node-key="id"
            :data="modelTreeData"
            :props="defaultProps"
            :filter-node-method="filterNode"
            show-checkbox
            @check="carModelCheck"
            ref="modeltree"
          >
          </el-tree>
          <div v-if="moreshow" @click="getmore">
            <a class="more">点击加载更多</a>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cardModelShow = false">取 消</el-button>
        <el-button type="primary" @click="carModelCheckval">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import api from "@/api/location/positioning";
export default {
  data() {
    return {
      activeName: "first",
      company: {
        allNum: 0,
        onlineNum: 0,
        offlineNum: 0,
      },
      input: "",
      companyTree: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      offLineSearch: false,
      dateTime: "",
      offLineNum: 0,
      activeNum: 1,

      areaTree: [],
      searchCarinfoShow: false,
      searchCarinfoForm: {
        classification: "", //分类
        cId: "",
        model: "", //型号
        mId: "",
        brand: "", //品牌
        bId: "",
      },

      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
        shortcuts: [
          {
            text: "离线一周",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            },
          },
          {
            text: "离线一个月",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", date);
            },
          },
          {
            text: "离线三个月",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", date);
            },
          },
        ],
      },

      cardTypeShow: false,
      cardBrandShow: false,
      cardModelShow: false,
      typeTreeData: [],
      brandTreeData: [],
      modelTreeData: [],
      filterText: "",
      brandfilterText: "",
      modelfilterText: "",
      moreshow: true,
      pageNo: 1,
    };
  },
  watch: {
    filterText(val) {
      // console.log(val);
      this.$refs.typetree.filter(val);
    },
    brandfilterText(val) {
      // console.log(val);
      this.$refs.brandtree.filter(val);
    },
    modelfilterText(val) {
      // console.log(val);
      this.$refs.modeltree.filter(val);
    },
  },
  mounted() {
    // this.getAearTree();
    this.getCompanyTree();
    this.count();
    this.timer = setInterval(() => {
      this.count();
    }, 10000);
  },
  destroyed() {
    clearInterval(this.timer);
    clearInterval(this.companyRound);
    clearInterval(this.areaRound);
  },
  methods: {
    count() {
      api.count().then((res) => {
        this.company = res.data;
      });
    },
    // 公司-区域tab切换
    handleClick(tab, b) {
      this.$emit("treeTableSelected", tab.name);
      if (tab.name == "first") {
        if (this.areaRound) {
          clearInterval(this.areaRound);
        }
        this.$refs.areaTree.setCheckedKeys([]);
        let data = localStorage.getItem("companyTree");
        this.count();
        if (data) {
          data = JSON.parse(data);
          this.$set(this, "companyTree", data);
        } else {
          this.getCompanyTree();
        }
      } else if (tab.name == "second") {
        if (this.companyRound) {
          clearInterval(this.companyRound);
        }
        if (this.areaTree.length == 0) {
          this.getAearTree();
        }
      }
    },
    getCompanyTree() {
      this.$set(this, "companyTree", [{ label: "加载中...", disabled: true }]);

      api.deptTree().then((res) => {
        // console.log("==========>", res);
        if (res.code == 200) {
          let result = [res.data];
          result.forEach((leveOne) => {
            leveOne.disabled = true;
            leveOne.children.forEach((leveTwo) => {
              leveTwo.disabled = true;
              leveTwo.children.forEach((leveThree) => {
                leveThree.disabled = true;
              });
            });
          });
          this.$set(this, "companyTree", result);
          localStorage.setItem("companyTree", JSON.stringify(result));
          // this.$set(this, "companyTree", res.data);
        }
      });
    },
    getAearTree() {
      this.$set(this, "areaTree", [{ label: "加载中...", disabled: true }]);
      api.districtTree().then((res) => {
        if (res.code == 200) {
          this.$set(this, "areaTree", res.data);
        }
        // console.log(this.areaTree);
      });
    },
    clickNum(val) {
      this.$set(this, "companyTree", [{ label: "加载中...", disabled: true }]);

      this.activeNum = val;
      this.companyKeySearch();
    },
    getOffLineNum() {
      this.offLineSearch = true;
    },
    companyCheck(node, val) {
      // console.log("=======>", node, val);
      if (val.checkedKeys.length > 0) {
        let arr = [];
        // let arr = val.checkedKeys;
        val.checkedNodes.forEach((item) => {
          if (item.configId) {
            // arr.push(item.terminalCode);
            arr.push(item.configId);
          }
        });
        this.cityId = arr.toString();
        // console.log(this.cityId);
        this.getCompanyInfo(this.cityId);
        if (this.companyRound) {
          console.log(1, "===========清除");
          clearInterval(this.companyRound);
        }
        this.companyRound = setInterval(() => {
          console.log(1, "===========轮循");
          this.getCompanyInfo(this.cityId);
          // }, 1000 * 5);
        }, 1000 * 60 * 2);
      } else {
        this.$emit("tableData", []);
      }
    },
    companyKeySearch() {
      let params = {
        searchValue: this.input,
        isOnline: this.activeNum == 1 ? "" : this.activeNum == 2 ? true : false, //是否在线 ? ,
        deptId: "",
      };
      api.groupCarTree(params).then((res) => {
        if (res.code == 200) {
          this.$set(this, "companyTree", res.data);
        }
      });
    },
    getCompanyInfo() {
      let params = { configIds: this.cityId };
      api.realTimeGps(params).then((res) => {
        // console.log("==========>", res);
        if (res.code == 200) {
          this.$emit("tableData", res.data);
        }
      });
    },
    //== 区域树复选框点击
    allcheck(nodes, val) {
      // console.log(val);
      //重置列表
      // this.$store.commit("changeAreaSearchCar", "");
      let obj = {
        allCarNum: [],
        notWorkNum: [],
        workNum: [],
        notWorkOtherNum: [],
      };
      this.$emit("sure", obj);
      if (val.checkedKeys.length > 0) {
        let arr = val.checkedKeys;
        this.areaCityId = arr.toString();
        // let data = {
        //   city: this.areaCityId,
        // };
        this.getCarInfo();
        if (this.areaRound) {
          console.log(1, "===========清除");
          clearInterval(this.areaRound);
        }
        this.areaRound = setInterval(() => {
          console.log(1, "===========轮循");
          this.getCarInfo(this.cityId);
          // }, 1000 * 5);
        }, 1000 * 60 * 2);
      }
    },
    // ==获取类型搜索列表
    searchCarinfo(val) {
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.5)",
      });
      if (val == "cartype") {
        api
          .carTypeTree()
          .then((res) => {
            console.log("====1>", res.data);
            loading.close();
            this.typeTreeData = res.data;
            this.cardTypeShow = true;
          })
          .catch((err) => {
            loading.close();
          });
      } else if (val == "carbrand") {
        api
          .carBrandList()
          .then((res) => {
            console.log("====2>", res.data);
            loading.close();
            this.brandTreeData = res.data;
            this.cardBrandShow = true;
          })
          .catch((err) => {
            loading.close();
          });
      } else if (val == "carmodel") {
        let params = {
          pageNum: this.pageNo,
          pageSize: 500,
        };
        api
          .carModelListPage(params)
          .then((res) => {
            console.log("====3>", res.data);
            loading.close();
            if (res.rows.length < 500) {
              this.moreshow = false;
            }
            this.modelTreeData = [...this.modelTreeData, ...res.rows];
            this.cardModelShow = true;
          })
          .catch((err) => {
            loading.close();
          });
        // this.$refs.modelpopup.init();
      }
    },
    getmore() {
      this.modelfilterText = "";
      this.pageNo += 1;
      this.searchCarinfo("carmodel");
    },
    cardModelClose() {
      this.modelTreeData = [];
      this.pageNo = 1;
    },
    //==区域下条件搜索
    searchBtn() {
      //console.log(this.searchCarinfoForm)
      let searchCondition = this.searchCarinfoForm;
      if (searchCondition.cId || searchCondition.mId || searchCondition.bId) {
        let obj = {
          carTypes: searchCondition.cId, // 分类
          brandIds: searchCondition.bId, // 品牌
          modelIds: searchCondition.mId, // 型号
        };
        this.getCarInfo(obj);
      }
    },
    //==区域表格数据
    getCarInfo(val = []) {
      let params = {
        cityIds: this.areaCityId,
        carTypes: val.carTypes,
        carBrand: val.brandIds,
        carModels: val.modelIds,
        typeIds: val.typeIds,
      };
      this.$emit("areaExportData", params);

      // const loading = this.$loading({
      //   lock: true,
      //   text: "Loading",
      //   spinner: "el-icon-loading",
      //   background: "rgba(0, 0, 0, 0.5)",
      // });
      api.realTimeCity(params).then((res) => {
        // console.log("=====res=====>", res);
        if (res.code == 200) {
          // loading.close();
          let data = res.data;
          this.getWorkNum(data);
          // data.loadNums = data.loadNums ? data.loadNums : []; //待机
          // data.workNums = data.workNums ? data.workNums : []; //工作
          // data.notWorkNums = data.notWorkNums ? data.notWorkNums : []; //未工作
          // let totalList = [...data.loadNums, ...data.workNums, ...data.notWorkNums];
          // this.$store.commit("changeAreaSearchCar", totalList);
        } else {
          setTimeout(() => {
            loading.close();
          }, 2000);
        }
      });
    },
    getOffLineCarNum() {
      if (this.dateTime) {
        api
          .offlineCount(this.dateTime)
          .then((res) => {
            this.offLineNum = res.data;
          })
          .catch((err) => {
            console.error(err);
          });
      }
    },
    //==整合工作分组数量
    getWorkNum(val) {
      // console.log("==val=====>", val);
      let allCarNum = [];
      let notWorkNum = [];
      let workNum = [];
      let notWorkOtherNum = [];
      allCarNum = [...val.workNums, ...val.loadNums, ...val.notWorkNums];
      notWorkNum = val.notWorkNums;
      workNum = val.workNums;
      notWorkOtherNum = val.loadNums;

      let obj = {
        allCarNum: allCarNum,
        notWorkNum: notWorkNum,
        workNum: workNum,
        notWorkOtherNum: notWorkOtherNum,
      };
      // console.log(obj);
      this.$emit("sure", obj);
    },
    resetBtn(formName) {
      // this.$refs[formName].resetFields();
      this.searchCarinfoForm = {};
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 车辆类型
    carTypeCheck(node, val) {
      if (val.checkedNodes.length > 0) {
        let arr = val.checkedNodes;
        this.carTypeCheckNode = arr.map((item) => {
          return {
            label: item.label,
            id: item.id,
          };
        });
      }
      // console.log(123, this.carTypeCheckNode);
    },
    checkedval() {
      let arr = this.carTypeCheckNode;
      let label = arr.map((e) => {
        return e.label;
      });
      let id = arr.map((e) => {
        return e.id;
      });
      let returnData = {
        label: label.toString(),
        id: id.toString(),
      };
      this.cardTypeShow = false;
      this.$refs.typetree.setCheckedKeys([]);
      this.searchCarinfoForm.classification = returnData.label;
      this.searchCarinfoForm.cId = returnData.id;
    },
    //车辆品牌
    carBrandCheck(node, val) {
      if (val.checkedNodes.length > 0) {
        let arr = val.checkedNodes;
        this.carBrandCheckNode = arr.map((item) => {
          return {
            label: item.label,
            id: item.id,
          };
        });
      }
      // console.log("车辆品牌", this.carBrandCheckNode);
    },
    carBrandCheckval() {
      let arr = this.carBrandCheckNode;
      let label = arr.map((e) => {
        return e.label;
      });
      let id = arr.map((e) => {
        return e.id;
      });
      let returnData = {
        label: label.toString(),
        id: id.toString(),
      };
      // console.log(returnData);
      this.cardBrandShow = false;
      this.$refs.brandtree.setCheckedKeys([]);
      this.searchCarinfoForm.brand = returnData.label;
      this.searchCarinfoForm.bId = returnData.id;
    },
    //车辆型号
    carModelCheck(node, val) {
      if (val.checkedNodes.length > 0) {
        let arr = val.checkedNodes;
        this.carModelCheckNode = arr.map((item) => {
          return {
            label: item.label,
            id: item.id,
          };
        });
      }
      // console.log("车辆型号", this.carModelCheckNode);
    },
    carModelCheckval() {
      let arr = this.carModelCheckNode;
      let label = arr.map((e) => {
        return e.label;
      });
      let id = arr.map((e) => {
        return e.id;
      });
      let returnData = {
        label: label.toString(),
        id: id.toString(),
      };
      this.cardModelShow = false;
      this.$refs.modeltree.setCheckedKeys([]);
      this.searchCarinfoForm.model = returnData.label;
      this.searchCarinfoForm.mId = returnData.id;
    },
  },
};
</script>

<style lang="scss" scoped>
.tree-container {
  max-height: 100%;
  .areaTree {
    height: calc(60vh - 100px) !important;
    overflow: scroll;
  }
  .numStatus {
    font-size: 13px;
    padding: 0 4px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
  }
  .active {
    font-weight: 700;
  }
  .searchbox {
    margin: 4px 0;
  }
  .treedata {
    height: calc(60vh - 124px) !important;
    overflow: scroll;
  }
  .searchCarinfobox {
    background: #fff;
    padding: 18px;
    margin: 4px;
    border: 1px solid #ccc;
    position: absolute;
    top: 44px;
    z-index: 99;
    .cpnc {
      margin-left: 6px;
    }
  }
}

::v-deep .el-dialog__body {
  padding: 10px 20px;
}
.flex-center {
  display: flex;
  align-items: center;
  justify-content: center;
}
.more {
  cursor: pointer;
  margin: 18px 0;
  display: flex;
  justify-content: center;
  font-size: 15px;
  color: rgb(65, 121, 206);
}
</style>
